package com.ulic.customerManApplication.mailmodule.action;

import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.base.BaseAction;
import com.ulic.customerManApplication.commonmodule.bo.BirthdayMessage;
import com.ulic.customerManApplication.commonmodule.bo.MailSignature;
import com.ulic.customerManApplication.commonmodule.bo.Organization;
import com.ulic.customerManApplication.commonmodule.vo.ImpDataInfor;
import com.ulic.customerManApplication.constant.CONSTANT;
import com.ulic.customerManApplication.mailmodule.bo.MailRecord;
import com.ulic.customerManApplication.mailmodule.service.MailService;
import com.ulic.customerManApplication.mailmodule.vo.MailRecordVO;
import com.ulic.customerManApplication.membermodule.bo.Member;
import com.ulic.customerManApplication.membermodule.service.MemberService;
import com.ulic.customerManApplication.membermodule.vo.MemberVO;
import com.ulic.customerManApplication.pager.PagerModel;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.util.config.ConfigInfo;
import com.ulic.customerManApplication.util.excel.DownloadFile;
import com.ulic.customerManApplication.util.excel.UploadFile;
import com.ulic.customerManApplication.util.mail.SendMail;

@Component("mailAction")
@Scope("prototype")
public class MailAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private MailService mailService;
	private MailRecord mailRecord;
	private BirthdayMessage birthdayMessage;
	private MailSignature mailSignature;
	private String impDataInfor;
	private MemberService memberService;
	private String signature;
	private String fileName;
	private List<File> attachFiles = new ArrayList<File>();

	public String getImpDataInfor() {
		return impDataInfor;
	}

	public void setImpDataInfor(String impDataInfor) {
		this.impDataInfor = impDataInfor;
	}

	public List<File> getAttachFiles() {
		return attachFiles;
	}

	public void setAttachFiles(List<File> attachFiles) {
		this.attachFiles = attachFiles;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public BirthdayMessage getBirthdayMessage() {
		return birthdayMessage;
	}

	public void setBirthdayMessage(BirthdayMessage birthdayMessage) {
		this.birthdayMessage = birthdayMessage;
	}

	public MailSignature getMailSignature() {
		return mailSignature;
	}

	public void setMailSignature(MailSignature mailSignature) {
		this.mailSignature = mailSignature;
	}

	public MailRecord getMailRecord() {
		return mailRecord;
	}

	public void setMailRecord(MailRecord mailRecord) {
		this.mailRecord = mailRecord;
	}

	public MailService getMailService() {
		return mailService;
	}

	public String getSignature() {
		return signature;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}

	@Resource
	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	@Resource
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		HttpServletRequest httpServletRequest = ServletActionContext
				.getRequest();
		PagerModel pm = mailService.getMailRecords(curPage);
		httpServletRequest.setAttribute("pm", pm);
		return SUCCESS;
	}

	public String searchMailRecords() throws Exception {
		HttpServletRequest httpServletRequest = ServletActionContext
				.getRequest();
		String startDate = httpServletRequest.getParameter("startDate");
		String endDate = httpServletRequest.getParameter("endDate");
		String roleName = (String) session.get("rolename");
		User user = (User) session.get(CONSTANT.USER_SESSION_KEY);
		MailRecordVO mailRecordVO = new MailRecordVO();
		mailRecordVO.setStartDate(startDate);
		mailRecordVO.setEndDate(endDate);
		mailRecordVO.setRoleName(roleName);
		mailRecordVO.setUser(user);
		mailRecordVO.setMailRecord(mailRecord);
		PagerModel pm = mailService.getMailRecords(mailRecordVO, curPage);
		httpServletRequest.setAttribute("pm", pm);
		httpServletRequest.setAttribute("startDate", startDate);
		httpServletRequest.setAttribute("endDate", endDate);
		return SUCCESS;
	}

	public String saveBirthdayBless() {
		User user = (User) session.get(CONSTANT.USER_SESSION_KEY);
		birthdayMessage.setUser(user);
		mailService.addBirthdayBless(birthdayMessage);
		return SUCCESS;
	}

	public String showBirthdayBless() {
		User user = (User) session.get(CONSTANT.USER_SESSION_KEY);
		birthdayMessage = mailService.getBirthdayMessageByType(user, "MAIL");
		return SUCCESS;
	}

	public String toGetReceives() {
		HttpServletRequest httpServletRequest = ServletActionContext
				.getRequest();
		MemberVO memberVO = new MemberVO();
		String roleName = (String) session.get("rolename");
		User user = (User) session.get(CONSTANT.USER_SESSION_KEY);
		memberVO.setRoleName(roleName);
		Member member = new Member();
		if ("SUBADMIN".equals(roleName)) {
			Organization organ = (Organization) session.get("barchList");
			if (organ != null) {
				member.setSubCompany(organ.getUm_organ_id());
			}
		} else if ("THIRDADMIN".equals(roleName)) {
			Organization subComOrgan = (Organization) session.get("barchList");
			if (subComOrgan != null) {
				member.setSubCompany(subComOrgan.getUm_organ_id());
			}
			Organization organ = (Organization) session.get("expensedList");
			if (organ != null) {
				member.setSubCity(organ.getUm_organ_id());
			}
		}
		memberVO.setMember(member);
		memberVO.setUser(user);
		PagerModel pm = memberService.getMembers(memberVO, curPage);
		httpServletRequest.setAttribute("members", memberService.getMembers(memberVO, pm.getTotal()).getDatas());
	    return SUCCESS;
	}

	public String toSendMail() {
		HttpServletRequest httpServletRequest = ServletActionContext
				.getRequest();
		PagerModel pm = memberService.getMembers(curPage);
		httpServletRequest.setAttribute("sender","unionlove");
		httpServletRequest.setAttribute("pm", pm);
		return SUCCESS;
	}

	/**
	 * 发送邮件
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public String sendMail() throws Exception {
		HttpServletRequest httpServletRequest = ServletActionContext
				.getRequest();
	    HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
	    PrintWriter out = httpServletResponse.getWriter();
		User user = (User) session.get(CONSTANT.USER_SESSION_KEY);
		String[] receives = httpServletRequest.getParameter("receiveId").split(
				";");// 获取收件人的ID
		String copyToId = httpServletRequest.getParameter("copyToId");// 获取抄送人的ID
		String[] copyTos = null;
		if (copyToId != null && copyToId.length() != 0) {
			copyTos = copyToId.split(";");
		}
		Set<Member> addressees = new HashSet<Member>();
		Set<Member> copiesTo = new HashSet<Member>();
		Member member = null;
		for (String reviceve : receives) {// 获取接收人
			if(reviceve!=null&&reviceve.length()!=0){
				member = memberService.getMember(Integer.parseInt(reviceve));
				addressees.add(member);
			}
		}
		if (copyTos != null && copyTos.length != 0) {
			for (String copyTo : copyTos) {// 获取抄送人
				member = memberService.getMember(Integer.parseInt(copyTo));
				copiesTo.add(member);
			}
		}
		long date = new Date().getTime();
		String realAttach = "";
		String upAttach = "";
		String attaches = "";
		int findex = 0;
		InputStream in = null;
		String[] fileNames = fileName.split(",");
		List<String> upAttaches = new ArrayList<String>();
		if (fileName != null && fileName.length() != 0) { // 获取附件
			try {
				for (File attachFile : attachFiles) {
					
					if(attachFile != null && attachFile.length() > 0){
					//	if(attachFile.length()<=10485760){
					
					realAttach = fileNames[findex].substring(fileNames[findex]
							.lastIndexOf("\\") + 1);
					upAttach = UploadFile.upload(attachFile, fileNames[findex],date);// 先将文件上传到服务器
					attaches = attaches + ";" + realAttach + ":" + upAttach;
					upAttaches.add(upAttach + "," + realAttach);
					findex++;
				//		}
					}
				}
			} catch (Exception e) { // TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sendTime = sdf.format(now);
		mailRecord.setCopiesTo(copiesTo);
		mailRecord.setSender(user);
		mailRecord.setSendTime(sendTime);
		mailRecord.setAttachments(attaches);
		mailSignature = mailService.getMailSignature(user);
		SendMail sendMail = new SendMail();
		String[] tos = new String[addressees.size()];
		String[] copies = new String[copiesTo.size()];
		int index = 0;
		int count = 0;
		for (Member m : addressees) {// 获取收件人的邮箱
			if (m.getEmail() != null && m.getEmail().length() != 0) {
				tos[index++] = m.getEmail();
			}
		}
		if (copyTos != null && copyTos.length != 0) {// 获取抄送人邮箱
			for (Member m : copiesTo) {
				if (m.getEmail() != null && m.getEmail().length() != 0) {
					copies[count++] = m.getEmail();
				}
			}
		}
		String srcPath = ConfigInfo.getPropertiesValue("uploadfile.path");
		for (String fname : upAttaches) {
			sendMail.attachfile(srcPath + "/" + fname);
		}
		String signature = mailSignature == null||mailSignature.getSignature()==null ? "" : "<br/><br/>"+new String(mailSignature
				.getSignature());
		List<String> successTos = sendMail.sendMails(tos, copies, mailRecord
				.getTheme(), mailRecord.getContent() , signature);// 发送邮件
		sendMail.deleteAttachFiles();

		ImpDataInfor impDataInfor = new ImpDataInfor();// 发送结果信息
		impDataInfor.setTotalNum(tos.length);// 总共发送封数
		impDataInfor.setSucceedNum(successTos.size());// 成功发送封数
		impDataInfor.setFailNum(tos.length - successTos.size());// 发送失败数
		this.setImpDataInfor(impDataInfor.toString());
		Set<Member> succeedAddressees = new HashSet<Member>();
		for (Member smember : addressees) {// 获取成功发送的收件人
			if (smember.getEmail() != null
					&& successTos.contains(smember.getEmail())) {
				succeedAddressees.add(smember);
			}
		}
		if (succeedAddressees.size() != 0) {// 如果成功发送为0，则不添加发送记录
			mailRecord.setAddressees(succeedAddressees);
			mailService.addMailRecords(mailRecord);
		}
		return SUCCESS;
	}

	public String viewMailRecord() throws Exception {
		HttpServletRequest httpServletRequest = ServletActionContext
				.getRequest();
		mailRecord = mailService.getMailRecordById(mailRecord.getMail_id());
		String attachments = mailRecord.getAttachments();
		String receives = "";
		String copies = "";
		List<String> upFiles = new ArrayList<String>();
		if (attachments != null && attachments.length() != 0) {
			String[] attaches = attachments.split(";");
			if (attaches != null && attaches.length != 0) {
				for (String attach : attaches) {
					if (attach != null && attach.length() != 0) {
						String[] fileNames = attach.split(":");
						// upFiles.add(URLEncoder.encode(URLEncoder.encode(fileNames[0],"UTF-8"),"UTF-8"));
						upFiles.add(fileNames[0]);
					}
				}
			}
		}
		for (Member receive : mailRecord.getAddressees()) {
			receives = receives + " " + receive.getMemberName();
		}
		if (mailRecord.getCopiesTo() != null
				&& mailRecord.getCopiesTo().size() != 0) {
			for (Member copy : mailRecord.getCopiesTo()) {
				copies = copies + " " + copy.getMemberName();
			}
		}
		httpServletRequest.setAttribute("upFiles", upFiles);
		httpServletRequest.setAttribute("copies", copies);
		httpServletRequest.setAttribute("receives", receives);
		return SUCCESS;
	}

	public String deleteMailRecord() {
		mailRecord = mailService.getMailRecordById(mailRecord.getMail_id());
		mailService.removeMailRecord(mailRecord);
		return SUCCESS;
	}

	@SuppressWarnings("deprecation")
	public String downloadAttach() throws Exception {
		HttpServletRequest httpServletRequest = ServletActionContext
				.getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext
				.getResponse();
		mailRecord = mailService.getMailRecordById(mailRecord.getMail_id());
		String fileId = httpServletRequest.getParameter("fileId");
		String downloadAttach = "";
		String attachments = mailRecord.getAttachments();
		if (attachments != null && attachments.length() != 0) {
			String[] attaches = attachments.split(";");
			if (attaches != null && attaches.length != 0) {
				for (int i = 1; i < attaches.length; i++) {
					if (i == Integer.parseInt(fileId)) {
						downloadAttach = attaches[i];
					}
				}
			}
		}
		String realPath = ConfigInfo.getPropertiesValue("uploadfile.path");
		DownloadFile.download(realPath, downloadAttach, httpServletRequest,
				httpServletResponse);// 从服务器上下载文件
		return null;
	}

	/**
	 * Description: 进入设置签名界面
	 * 
	 * @Version1.0 2012-9-10 下午05:40:54 李求智 (liqz@huilan.com) created
	 * @return
	 */
	public String setSignature() {
		User user = (User) session.get(CONSTANT.USER_SESSION_KEY);
		mailSignature = mailService.getMailSignature(user);
		if (mailSignature != null &&mailSignature.getSignature()!=null) {
			signature = new String(mailSignature.getSignature());
		} else {
			signature = "";
		}
		return SUCCESS;
	}

	/**
	 * Description: 设置签名
	 * 
	 * @Version1.0 2012-9-10 下午05:41:09 李求智 (liqz@huilan.com) created
	 * @return
	 */
	public String saveMailSignatrue() {
		try {
			User user = (User) session.get(CONSTANT.USER_SESSION_KEY);
			if(mailSignature == null){
				mailSignature = new MailSignature();
			}
			mailSignature.setSignature(signature.getBytes());
			mailSignature.setUser(user);
			mailService.saveMailSignature(mailSignature);
		} catch (Exception e) {
			// e.printStackTrace();
			request.put("message", e.getMessage());
			return "fail";
		}
		return SUCCESS;
	}
}
